<template>
  <div class="RenderArea" ref="RenderArea"></div>
</template>

<script>
import * as THREE from 'three';
import a001 from './images/a_001.png';

export default {
  mounted() {
    const RenderArea = this.$refs.RenderArea;
    const scene = new THREE.Scene();

    const camera = new THREE.PerspectiveCamera(
      75,
      window.innerWidth / window.innerHeight,
      0.1,
      1000
    );

    // 移动相机位置
    camera.position.z = 2;

    const renderer = new THREE.WebGLRenderer(3, 3, 3);
    renderer.setSize(window.innerWidth, window.innerHeight);
    RenderArea.appendChild(renderer.domElement);

    const textureLoader = new THREE.TextureLoader();
    // const texture = textureLoader.load(a001);// 可以直接设置图片
    const texture = textureLoader.load(
      a001, // './images/a_001.png', // 需要放在public的images下面
      function (texture) {
        console.log('texture:', texture);
        material.map = texture; // 在材质中设置贴图属性
        material.needsUpdate = true; // 通知渲染器需要更新材质
      },
      function (xhr) {
        console.log((xhr.loaded / xhr.total) * 100 + '% loaded'); // 贴图加载进度
      },
      function (err) {
        console.log('An error happened'); // 贴图加载错误处理
      }
    );
    const geometry = new THREE.BoxGeometry();
    const material = new THREE.MeshBasicMaterial({
      // color: 0x00ff00,// 会变成绿色
      map: texture,
    });
    const cube = new THREE.Mesh(geometry, material);
    scene.add(cube);

    function animate() {
      requestAnimationFrame(animate);
      cube.rotation.x += 0.01;
      cube.rotation.y += 0.01;
      renderer.render(scene, camera);
    }
    animate();
  },
};
</script>
